<template>
  <div>
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right; margin-right: 30px" type="primary" @click="handleSearch()" size="small">
          查询
        </el-button>
        <el-button style="float:right;margin-right: 15px" @click="handleResetSearch()" size="small">
          重置
        </el-button>
      </div>

      <div style="margin-top: 30px; ">
        <el-form style="display: inline-block;">
          <!-- <el-form :inline="true" :model="listQuery" size="small" label-width="140px"> -->
          <div style="display: inline-block;margin-left:20px">
            <el-form-item label="输入搜索：">
              <el-input v-model="searchForm.orderSn" class="input-width" placeholder="输入订单编号"></el-input>
            </el-form-item>
          </div>
          <div style="display: inline-block;margin-left:20px">
            <el-form-item label="档口号：">
              <el-input v-model="searchForm.stallNum" class="input-width" placeholder="输入档口号"></el-input>
            </el-form-item>
          </div>
          <div style="display: inline-block;margin-left:20px">
            <!-- <el-form-item label="订单状态：">
              <el-tree-select v-model="searchForm.status" :data="productCategoryOptions"
                              :render-after-expand="false" style="width: 120px" clearable/>
            </el-form-item> -->
            <el-form-item prop="status" label="小组状态：">
              <el-select class="input-width" v-model="searchForm.status" placeholder="选择状态" style="width: 200px;" clearable>
                  <el-option style="width: 200px;" :value="0" label="待分配">
                    </el-option>
                      <el-option style="width: 200px;" :value="1" label="待卸货">
                    </el-option>
                    <el-option style="width: 200px;" :value="2" label="待付款">
                    </el-option>
                    <el-option style="width: 200px;" :value="3" label="已完成">
                    </el-option>
                    <el-option style="width: 200px;" :value="4" label="已关闭">
                    </el-option>
                </el-select>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
  <div class="table-container" style="margin-top: 10px;">
    <el-table width="120px" ref="multipleTable" :data="list" tooltip-effect="dark" border style="width: 100%" stripe>
      <el-table-column fixed prop="orderSn" label="订单编号" width="140px" style="margin-left:20px;" align="center"/>
      <el-table-column prop="createTime" label="提交时间" width="120px"/>
      <el-table-column prop="unloadTime" label="卸货时间" width="150px"></el-table-column>
      <el-table-column prop="userName" label="用户名" width="120px"/>
      <el-table-column prop="payAmount" label="实际应付金额" width="120px"></el-table-column>
      <el-table-column prop="note" label="备注信息"></el-table-column>
      <el-table-column prop="stallNum" label="档口号" width=""></el-table-column>
      <el-table-column prop="status" label="订单状态" width="120px">

        <template #default="scope">
          <!-- <el-tag :type="scope.row.status? 'success' : 'danger' ">
              {{ scope.row.status ==='0'?'已分配': '待分配'}}
            </el-tag > -->
          <el-tag v-if="scope.row.status == 0" :type="'danger'">
            待分配
          </el-tag>
          <el-tag v-else-if="scope.row.status == 1">
            待卸货
          </el-tag>
          <el-tag v-else-if="scope.row.status == 2"  :type="'warning'">
            待付款
          </el-tag>
          <el-tag v-else-if="scope.row.status == 3" :type="'success'">
            已完成
          </el-tag>
          <el-tag v-else-if="scope.row.status == 4">
            已关闭
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="详情" width="140px">
        <template #default="scope">
          <el-button size="default" plain @click="onRowClick(scope.row.orderId)">
            货品详情
          </el-button>
          <br>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="编辑" width="120" class="operate-button-container">
        <template #default="scope">
          <el-button type="primary" size="small" @click="onRowClick1(scope.row)">
            查看订单
          </el-button>
          <br>
          <el-button style="margin-top: 5px;" type="danger" size="small">关闭订单</el-button>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120" class="operate-button-container">
        <template #default="scope">
          <el-button type="primary" size="small"  v-if="scope.row.status === 0"  @click="onRowClick3(scope.row.orderId)">
            分配工人
          </el-button>
          <br>
          <el-button plain size="small" style="margin-top: 5px;"
                     @click="onRowClick2(scope.row)"
                     v-if="scope.row.status === 0 || scope.row.status === 1"
                     >
            填写磅单
          </el-button>
          <br>
          <el-button plain size="small" style="margin-top: 5px;"
                     @click="moneyCheck(scope.row)">
            收款记录
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-dialog title="货品详情" width="1200" v-model="dialogTableVisible1">
      <el-table :data="proData" v-loading="listLoading">
        <el-table-column prop="prodName" label="产品名称"></el-table-column>
        <el-table-column prop="prodPrice" label="卸货价格"> </el-table-column>
        <el-table-column prop="prodUnit" label="单位"></el-table-column>
        <!-- <el-table-column prop="priceRules" label="货品价格规则">
        </el-table-column> -->
      </el-table>
    </el-dialog>
    <el-dialog title="详情" width="1200" v-model="dialogTableVisible3">
      <el-table :data="[Download1]">
        <el-table-column prop="senderCar" label="配送车牌号" width=""></el-table-column>
        <el-table-column prop="senderName" label="驾驶员姓名" width=""></el-table-column>
        <el-table-column prop="senderPhone" label="驾驶员电话" width=""></el-table-column>

      </el-table>
      <br/>
      <el-table :data="[Download1]" title="订单详情" style="margin-top: 50px;">
        <el-table-column prop="address" label="详细地址" width=""></el-table-column>
        <el-table-column prop="note" label="订单备注" width=""></el-table-column>
        <el-table-column prop="status" label="确认支付状态" width=""></el-table-column>
        <el-table-column prop="totalAmount" label="预估总金额" width="120px"></el-table-column>
        <el-table-column prop="payType" label="支付方式" width=""></el-table-column>
        <el-table-column prop="payTime" label="支付时间" width=""></el-table-column>
        <el-table-column prop="otherAmount" label="其他费用" width="120px"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="分配工人" v-model="dialogTableVisible4" width="1200">
      <div v-loading="dialogTableLoading4">
        <div style="text-align: right;">
          <el-button type="warning" size="small" @click="refreshAllocationList">
            刷新数据
          </el-button>
          <el-tooltip content="向待通知的员工发送通知，以确认是否参与卸货" placement="top" effect="light">
            <el-button type="primary" size="small" @click="AllocateMembersFunc">
              发送通知
            </el-button>
          </el-tooltip>
        </div>
        <span style="margin-top: 20px; display: block; text-align: center;color: cornflowerblue;font-size: larger;"
              class="center-vertically">小组人员</span>
        <el-table v-loading="allocateMemberLoading" :span-method="objectSpanMethod" :data="data1" width="auto" border>
          <el-table-column prop="groupName" label="小组名" width="200px">
            <template #header>
              <el-input size="small" style="width: 100px" v-model="allocateSearchData.groupName" class="input-width"
                        placeholder="查询小组名" @change="refreshAllocationList"></el-input>
              <el-button style="margin-left: 10px" type="primary" @click="refreshAllocationList"
                         size="small">
                查询
              </el-button>
            </template>
            <template #default="{ row }">
              <!-- 全选复选框 -->
              <el-checkbox v-model="row.allChecked" @change="toggleAllMembers(row)">
                {{ row.groupName }}
              </el-checkbox>
            </template>
          </el-table-column>
          <el-table-column prop="users" label="小组成员" width="auto">
            <template #default="{ row }">
              <div style="display: flex; flex-direction: column; flex-wrap: nowrap; overflow-x: auto;">
                <div style="display: flex; flex-wrap: nowrap; overflow-x: auto;">
                  <el-checkbox v-for="member in row.members" :key="member.memberId" v-model="member.checked"
                               :disabled="member.disabled" :label="member.memberName" size="large"
                               style="margin-right: 10px;"
                               @change="handleCheckboxChange(member, row)">
                    {{ member.memberName }} <!-- 显示组员名称 -->
                  </el-checkbox>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination size="default" style="float: right;margin-top: 5px" layout="total, sizes, prev, pager, next"
                       @change="refreshAllocationList" background :total="Number(allocateSearchData.total)"
                       v-model:current-page="allocateSearchData.pageNum"
                       v-model:page-size="allocateSearchData.pageSize" v-model:page-sizes="allocateUserPageSizes"/>

        <span style="margin-top: 40px; display: block; text-align: center;color: cornflowerblue;font-size: larger;"
              class="center-vertically">已选择</span>
        <el-tabs v-model="allocateSelectTabName" type="card" size="large">
          <el-tab-pane name="fail">
            <template #label>
              <el-badge :value="unloadData.filter(item=>item.status != 2).length">
                <p>未参与</p>
              </el-badge>
            </template>
            <el-table v-loading="allocateListLoading" :data="unloadData.filter(item=>item.status != 2)" border>
              <el-table-column prop="groupName" label="小组名"></el-table-column>
              <el-table-column prop="groupUserName" label="所选成员"></el-table-column>
              <el-table-column prop="status" label="当前状态">
                <template #default="scope">
                  <el-tag v-if="scope.row.status == -1">
                    待通知
                  </el-tag>
                  <el-tag v-else-if="scope.row.status == 0" type="warning">
                    待确认
                  </el-tag>
                  <el-tag v-else-if="scope.row.status == 1" type="danger">
                    拒绝
                  </el-tag>
                  <el-tag v-else-if="scope.row.status == 2">
                    参与
                  </el-tag>
                  <el-tag v-else-if="scope.row.status == 3">
                    已发工资
                  </el-tag>
                  <el-tag v-else-if="scope.row.status == 4" type="danger">
                    超时
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column width="100px" label="操作">
                <template #default="scope">
                  <el-button v-if="scope.row.status != -1" type="danger" size="small"
                             @click="deleteAllocatedUser(scope.row)">撤回
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane name="success">
            <template #label>
              <el-badge :value="unloadData.filter(item=>item.status == 2).length" type="success">
                <p>已参与</p>
              </el-badge>
            </template>
            <el-table v-loading="allocateListLoading" :data="unloadData.filter(item=>item.status == 2)" border>
              <el-table-column prop="groupName" label="小组名"></el-table-column>
              <el-table-column prop="groupUserName" label="所选成员"></el-table-column>
              <el-table-column prop="status" label="当前状态">
                <template #default="scope">
                  <el-tag v-if="scope.row.status == -1">
                    未通知
                  </el-tag>
                  <el-tag v-else-if="scope.row.status == 0">
                    待确认
                  </el-tag>
                  <el-tag v-else-if="scope.row.status == 1" type="danger">
                    拒绝
                  </el-tag>
                  <el-tag v-else-if="scope.row.status == 2">
                    参与
                  </el-tag>
                  <el-tag v-else-if="scope.row.status == 3">
                    已发工资
                  </el-tag>
                  <el-tag v-else-if="scope.row.status == 4" type="danger">
                    超时
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
            <div class="mt-20 w-full flex justify-end">
              <el-button style="margin-top: 20px; float: right;" type="primary" :loading="allocateStartUnloadLoading"
                         @click="startUnloadFunc"
                         :disabled="unloadData.filter(item=>item.status == 2).length == 0">
                开始卸货
              </el-button>
            </div>
          </el-tab-pane>
        </el-tabs>

      </div>
    </el-dialog>
    <el-dialog title="上传凭证" v-model="dialogTableVisible5" style="height: auto;width: 80%;">
      <div id="app">
        <div class="container">

          <div class="image-container1">
            <el-image
                v-for="(url, index) in state.urls"
                :key="url"
                :src="url ? url : '../../../../public/unloadPictrue.png'"
                :initial-index="index"
                fit="contain"
                style="width: 100%; height: 100%;"
                lazy
                @click="showImage(url)"
            />
          </div>

          <div class="form-container">
            <el-form ref="ruleFormRef" style="width: 600px" :model="picParams" :rules="rules" label-width="auto"
                     class="form_style" status-icon>
              <el-form-item props="accessSn" label="入场单据号:">
                <el-input v-model="picParams.accessSn"/>
              </el-form-item>
              <el-form-item props="accessTime" label="入 场 时 间:">
                <!--                <el-input v-model="picParams.accessTime"/>-->
                <el-date-picker
                    style="width: 100%"
                    v-model="picParams.accessTime"
                    type="datetime"
                    placeholder="请选择入场时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item props="shopSn" label="商 户 编 号:">
                <el-input v-model="picParams.shopSn"/>
              </el-form-item>
              <el-form-item props="shopOwner" label="商 户 姓 名:">
                <el-input v-model="picParams.shopOwner"/>
              </el-form-item>
              <el-form-item props="truckLicense" label="车&nbsp&nbsp&nbsp牌&nbsp&nbsp&nbsp号:">
                <el-input v-model="picParams.truckLicense"/>
              </el-form-item>
              <el-form-item props="grossWight" label="车 辆 毛 重:">
                <el-input v-model="picParams.grossWeight"/>
              </el-form-item>
              <el-form-item props="tareWight" label="车 辆 皮 重:">
                <el-input v-model="picParams.tareWeight"/>
              </el-form-item>
              <el-form-item props="goodWight" label="货 物 净 重:">
                <el-input v-model="picParams.goodWeight"/>
              </el-form-item>
              <el-form-item props="goodType" label="货 物 类 型:">
                <el-input v-model="picParams.goodType"/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" style="margin-left: 50%;" @click="confirm()">提交</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div>

        <el-dialog
            v-model="dialogVisiblePic"
            title="磅单图片1"
            style="width: 800px; height: 800px;"
            draggable
            :modal="false"
            :lock-scroll="false"
            :close-on-click-modal="false"
            modal-class="modal-wrap"
            class="dialog-wrap"
        >
          <div
              class="image-container"
              @mousedown="startDragging"
              @mouseup="stopDragging"
              @mousemove="dragImage"
              @wheel="resizeImage"
          >
            <img
                :src="currentImageUrl"
                :style="imageStyle"
                ref="dialogImage"
                draggable="false"
            />
          </div>
        </el-dialog>
      </div>

    </el-dialog>
    <el-dialog title="收款信息记录" v-model="dialogTableVisible6">
      <div>
        <el-form :model="transferData">
          <el-form-item props="payee" label="收款人：">
            <el-input v-model="transferData.payee"/>
          </el-form-item>
          <el-form-item props="paidAmount" label="收款金额：">
            <el-input v-model="transferData.paidAmount"/>
          </el-form-item>
          <el-form-item props="payer" label="付款人：">
            <el-input v-model="transferData.payer"/>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" style="margin-left: 50%;" @click="confirmMoney()">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>

  <el-pagination size="default" style="float: right;margin-top: 5px" background
                 layout="total, sizes, prev, pager, next"
                 @change="handleSearchPaginationChange"
                 :total="Number(tableData.total)"
                 v-model:current-page="searchForm.pageNum"
                 v-model:page-size="searchForm.pageSize"
                 v-model:page-sizes="allocateUserPageSizes"/>
                 <!-- <span> {{ Number(tableData.total) }}</span> -->
</template>

<script lang="ts" setup>

import {ref, reactive, onMounted, VueElement} from 'vue'
import {Delete, Download, Plus, ZoomIn} from '@element-plus/icons-vue'
import {rowContextKey, SCOPE, type UploadFile} from 'element-plus'
import {ElMessage, ElMessageBox} from 'element-plus'
import type {ComponentSize, FormInstance, FormRules} from 'element-plus'

import {
  orderList,
  getProductDetail,
  getOrderUnload,
  getWorker,
  groupList,
  getUnallocatedUsers,
  updateOrderStatus,
  deleteAllocatedOrderUser,
  AllocateMembers,
  getUnallocateMan,
  getPictrueData,
  getOfflinePay
} from '../../../api';
import {id} from 'element-plus/es/locales.mjs';
import {Loading} from 'element-plus/es/components/loading/src/service.mjs';

//数据表数据
// const tableData = reactive({
//   list:[]
// })

const allocateUserPageSizes = ref([5, 10, 20, 30, 50, 100])
const dialogVisiblePic = ref(false)
const backgroundInput = ref('')
const currentImageUrl = ref('')
const showImage = (url) => {
  imageStyle.value = { ...imageStyleInit.value }; // 复制初始样式
  console.log('url', url)
  currentImageUrl.value = url
  console.log('图片', currentImageUrl)
  dialogVisiblePic.value = true

}
const imageStyle = ref({
  width: '600px',  // Initial width
  height: 'auto', // Maintain aspect ratio
  draggable: "false",
  position: 'relative',
  left: '0px',
  top: '0px'
});
const imageStyleInit = ref({
  width: '600px',  // Initial width
  height: 'auto', // Maintain aspect ratio
  draggable: "false",
  position: 'relative',
  left: '0px',
  top: '0px'
});

let isDragging = ref(false);
let startX = ref(0);
let startY = ref(0);
const dialogImage = ref(null);
const imgdragstart = (event) => {
  event.preventDefault();
};
dialogImage.ondragstart = imgdragstart;

const startDragging = (event: MouseEvent) => {
  isDragging.value = true;
  startX.value = event.clientX - parseInt(imageStyle.value.left);
  startY.value = event.clientY - parseInt(imageStyle.value.top);
  document.addEventListener('mouseup', stopDragging);
  document.addEventListener('mousemove', dragImage);
};

const stopDragging = () => {
  isDragging.value = false;
  document.removeEventListener('mouseup', stopDragging);
  document.removeEventListener('mousemove', dragImage);
};

const dragImage = (event: MouseEvent) => {
  if (isDragging.value) {
    imageStyle.value.left = `${event.clientX - startX.value}px`;
    imageStyle.value.top = `${event.clientY - startY.value}px`;
  }
};

const resizeImage = (event: WheelEvent) => {
  const delta = event.deltaY > 0 ? -20 : 20; // Change size by 10 pixels
  const currentWidth = parseInt(imageStyle.value.width);
  imageStyle.value.width = `${Math.max(currentWidth + delta, 10)}px`; // Minimum width 10px
  imageStyle.value.height = 'auto'; // Maintain aspect ratio
};


console.log('111', currentImageUrl)

onMounted(() => {
  getList()
  //getDetailList()
  getUnallocate()
  //getData()
})
const totalItems = ref(0);
const list = ref([]);
const tableData = ref({
  orderSn: '',
  stallNum: '',
  pageNum: 1,
  pageSize: 10,
  total: "",
  totalPage: '',
  status: ''
});

const getList = async () => {
  let res = await orderList(searchForm)
  tableData.value =res.data.list
  //console.log('resres.datas', res.data)
  list.value = res.data.list
  console.log(' list.value', list.value)
  console.log(' tableData.value', tableData.value)
  tableData.value.total = Number(res.data.total)
  console.log(' tableData.total', tableData.value.total)
        tableData.totalPage = res.data.totalPage
        searchForm.pageNum = res.data.pageNum
        searchForm.pageSize = res.data.pageSize

}

const handleSearchPaginationChange = () => {
  getList()
}

const getData = () => {
  getOrderByPage(searchForm.value)
      .then((response) => {
        tableData = response.data;
        console.log('dangqiande', response.data)
        tableData.total = Number(response.data.total)
        tableData.totalPage = response.data.totalPage
        queryParams.pageNum = response.data.pageNum
        queryParams.pageSize = response.data.pageSize
        console.log('23456y', tableData)
      })

};

//填写收款信息
let transferData = ref({
  orderId: '',
  paidAmount: '',
  payee: '',
  payer: ''
})

const confirmMoney = async () => {
  console.log('当前行23456', res);
  console.log('填写内容', transferData.value);

  transferData.value.orderId = Monorderid;

  console.log('填写内容4', transferData.value.orderId);
  console.log('填写内容transferData', transferData.value);
  let res1 = await getOfflinePay(transferData);
  console.log('查看一下', res1)
  if (res1.code == 200) {
    ElMessage({
      message: '添加成功',
      type: 'success',
      duration: 1000
    });
  } else {
    ElMessage({
      message: res1.message,
      type: 'error',
      duration: 1000
    });
  }
}

const allocateStartUnloadLoading = ref(false);
const proData = ref([]);
const orderOtherDetail = ref([]);
const Download1 = ref([]);
const total = ref(0);
const listLoading = ref(true);
const listLoading6 = ref(true);
const dialogTableVisible1 = ref(false)
const dialogTableVisible3 = ref(false)
const dialogTableVisible4 = ref(false)

const onRowClick = (orderId) => {
  console.log('kkkkkk', orderId)
  dialogTableVisible1.value = true
  getDetailList(orderId)
};

const res = ref(0)
const getDetailList = async (orderId) => {
  listLoading.value = true;
  console.log('444455', orderId)   // orderId已经拿到
  try {
    // let res = orderId
    // console.log('res',res)
    const response = await getProductDetail(orderId);
   // console.log('proData.value', response.data);
    console.log('respose.data', response.data);
    proData.value = response.data.prods;

  if (response.data && Array.isArray(response.data.prods)) {
      proData.value = response.data.prods.map(item => ({
        ...item,
        prodPrice: item.prodPrice / 100,  // 将 prodPrice 缩小 100 倍
      }));
    } else {
      console.error('未找到产品数组，检查响应结构:', response.data);
    }
    Download1.value = response.data;
    orderOtherDetail.value = response.data;
  } finally {
    listLoading.value = false;
  }
};

//订单详情
const onRowClick1 = (order) => {
  console.log("order:", order);
  dialogTableVisible3.value = true
  // getDetailList1(order)
  Download1.value = order
  console.log("Download3: ", Download1)
};


const getDetailList1 = async (orderId) => {
  try {
    const response = await getProductDetail(orderId);
    if (response.code === 200) {
      // 处理逻辑
    } else {
      console.error('Error fetching data:', response.message);
    }
  } catch (error) {
    console.error('An error occurred:', error);
  }
};
// const response = await getProductDetail(orderId);
// console.log('proData.value', response);
// console.log('response.data 的类型:', typeof response.data);
// orderOtherDetail.value = {
//         address: data.address,
//         note: data.note,
//         status: data.status,
//         payType: data.payType,
//         payTime: data.payTime,
//         otherAmount: data.otherAmount,
//         receiveTime: data.unloadTime // Adjust this based on your actual needs
//     };

//  orderOtherDetail.value = { ...response.data };
//     Download1.value =  { ...response.data };
//    // orderOtherDetail.value = response.data;

//    console.log('2334',orderOtherDetail.value)
// };

// const getDetailList1 = async (orderId) => {
//   listLoading6.value = true;
//   try{
//     console.log('444455',orderId)   // orderId传入
//     const response = await getProductDetail(orderId);
//     console.log('proData.value', response.data);
//     console.log('respose.data', response.data);
//    // proData.value= response.data.prods;
//     Download1.value = response.data;
//     orderOtherDetail.value = response.data;
//     console.log('748564796549',Download1.value)
//   } finally {
//     listLoading16.value = false;
//   }
// };

//查看订单数据


let getPicData = {
  groupId: '',
  orderId: '',
}

const state = reactive({
  urls: []
});
const orderID = []
//凭证图片数据
const dialogTableVisible5 = ref(false)
const onRowClick2 = async (row) => {
  console.log('row', row);
  console.log('group', row.groups);
  dialogTableVisible5.value = true;
  if (row.groups && row.groups.length > 0) {
    const groupId = row.groups[0].groupId;
    console.log('groupId:', groupId);
    getPicData.groupId = groupId

  } else {
    console.log('没有找到 group');
  }
  getPicData.orderId = row.orderId; // 将 row.orderId 赋值给 getPicData.orderId

  console.log('getPic', getPicData);

  try {
    const res = await getOrderUnload(getPicData);
    console.log('Response code:', res.code);
    console.log('apiData', res);
    // 将 res.data.pics 赋值给响应式对象的 urls
    state.urls = res.data.pics;
    console.log('Response data:', res.data.pics);
    console.log('state.urls:', state.urls);

  } catch (error) {
    console.error('Error:', error);
  }
}

//图片窗口


//填写凭证信息

let picParams = ref({
//   accessSn: '',
//  // accessTime: new Date(),
//  accessTime:'2024-12-03T06:57:31.938Z',
//   goodType: '',
//   goodWeight: '',
//   grossWeight: '',
//   groupId: '',
//   orderId: '',
//   shopOwner: '',
//   shopSn: '',
//   tareWeight: '',
//   truckLicense: ''
accessSn: "string",
accessTime: "2024-12-03T06:57:31.938Z",
goodType: 0,
  goodWeight: 0,
  grossWeight: 0,
  groupId: 0,
  orderId: 0,
  shopOwner: "string",
  shopSn: "string",
  tareWeight: 0,
  truckLicense: "string"
})

const confirm = async () => {
  //console.log('填写内容', picParams)
  console.log('填写内容', picParams.value)
  picParams.value.orderId = getPicData.orderId;
  picParams.value.groupId = getPicData.groupId;

  console.log('看看点击提交', picParams.value);
  console.log('看看点击提交', picParams)
  let res = await getPictrueData(picParams.value);
  console.log('查看一下', res)
  if (res.code == 200) {
    ElMessage({
      message: '添加成功',
      type: 'success',
      duration: 1000
    });
    //  handleResetSearch()
  } else {
    ElMessage({
      message: res.message,
      type: 'error',
      duration: 1000
    });
  }
}

const allocateSelectTabName = ref('fail')

const handleResetSearch = async () => {
  searchForm.value = {
  orderSn: '',
  stallNum: '',
  status: '',
  pageNum: 1,
  pageSize: 10,
  
}
  handleSearch()
}
//分配小组


const dialogTableLoading4 = ref(false)
const AllocateMembersFunc = async () => {
  // 筛选 status 为 -1 的成员，并按 groupId 添加到 allocateData.groups 中
  allocateData.groups = [];
  unloadData.value
      .filter(member => member.status === -1) // 只处理 status 为 -1 的数据
      .forEach(member => {
        // 查找 allocateData 中是否已有该组
        let group = allocateData.groups.find(g => g.groupId == member.groupId);
        if (group) {
          // 如果找到该组，向 groupUserIds 添加成员的 groupUserId
          group.groupUserIds.push(member.groupUserId);
        } else {
          // 如果未找到该组，创建新的组并加入 allocateData.groups
          allocateData.groups.push({
            groupId: member.groupId,
            groupUserIds: [member.groupUserId]
          });
        }
      });
  console.log('allocateData', allocateData)
  dialogTableLoading4.value = true
  let res = await AllocateMembers(allocateData)
  console.log('res', res)
  if (res.code == 200) {
    ElMessage({
      message: '发送成功',
      type: 'success',
    })

    //清空所有为true的值
    data1.value.forEach(group => {
      group.members.forEach(member => {
        member.checked = false;
      });
    })


  } else {
    ElMessage({
      message: res.message,
      type: 'error',
    })
  }

  dialogTableLoading4.value = false
  getmemberList(allocateData.orderId)
  refreshAllocationList()
}

const refreshAllocationList = async () => {
  await getmemberList(allocateData.orderId)
  getunload(allocateData.orderId)
}

const refreshAllocationListTimer = setInterval(() => {
  if (dialogTableVisible4.value == true) {
    refreshAllocationList()
  }
}, 1000 * 60 * 2);

const deleteAllocatedUser = async (member) => {
  await ElMessageBox.confirm(
      "是否撤回对该人员的分配，撤回后该人员将不会参与此次卸货",
      '注意',
      {
        confirmButtonText: '撤回',
        cancelButtonText: '暂不撤回',
        type: 'warning',
      }
  )
      .then(async () => {
            const {data, code, message} = await deleteAllocatedOrderUser(allocateData.orderId, member.groupUserId)
            if (code == 200) {
              ElMessage({
                message: '撤回成功',
                type: 'success',
              })
              refreshAllocationList()
            } else {
              ElMessage({
                message: message,
                type: 'error',
              })
            }
          }
      )
      .catch(() => {
        return
      })
}

const startUnloadFunc = async () => {
  allocateStartUnloadLoading.value = true;
  // await refreshAllocationList();
  await ElMessageBox.confirm(
      "是否开始卸货",
      '注意',
      {
        confirmButtonText: '开始',
        cancelButtonText: '暂不开始',
        type: 'warning',
      }
  )
      .then(async () => {
            const {code, data, message} = await updateOrderStatus(allocateData.orderId, 1)
            if (code == 200) {
              dialogTableVisible4.value = false
              ElMessage({
                type: 'success',
                message: '开始等待工人卸货',
              })
            } else {
              ElMessage({
                type: 'error',
                message: message,
              })
            }
          }
      )
      .catch(() => {
        return
      })
  allocateStartUnloadLoading.value = false;
}


const unloadData = ref([])

//分配小组信息显示

let allocateData = {
  groups: [],
  orderId: 0
}

const onRowClick3 = (orderId) => {
  allocateSearchData.value = {
    groupName: "",
    pageNum: 1,
    pageSize: 5,
    total: 0,
    totalPage: 0,
  }
  allocateData = {
    groups: [],
    orderId: 0
  }
  data1.value = []


  dialogTableVisible4.value = true
  getunload(orderId)
  // getGroupList()
  getmemberList(orderId)
  allocateData.orderId = orderId
  console.log('orderId', allocateData)
};

const groupNames = []; // 在函数外部定义
const groupUserNames = []; // 在函数外部定义

// let data = {
//   groupName: '',
//   pageNum: 1,
//   pageSize: 100,
//   status: ''
// }

const allocateSearchData = ref(null)

const allocateListLoading = ref(false)

const getunload = async (orderId) => {
  allocateListLoading.value = true
  const response = await getWorker(orderId);
  allocateListLoading.value = false
  unloadData.value = response.data; // 假设 response.data 是原始数据
  let res = response.data;

  if (Array.isArray(res)) {
    // res.forEach(item => {
    //   groupNames.push(item.groupName);
    //   groupUserNames.push(item.groupUserName);
    // });
    // // 组合数据并赋值给 unloadData
    // unloadData.value = res.map((item, index) => ({
    //   groupName: item.groupName,
    //   groupUserName: item.groupUserName,
    //   status: item.status
    // }));
    console.log("unloadData.value", unloadData.value)
    // 提取出订单员工的id集合
    const unloaderIdList = unloadData.value
        .filter(member => !"14".includes(member.status)) //可以重新请求的员工状态
        .map(unloadDataUser => unloadDataUser.groupUserId)

    // 筛选出 checked 为 true 的成员，并附加到 unloadData 中
    const checkedMembers = data1.value.flatMap(group =>
        group.members
            .filter(member => member.checked && !unloaderIdList.includes(member.memberId)) //第二个条件是确保成员不在 unloadData 中
            .map(member => ({
              confirmTime: "",
              distributeTime: "",
              endTime: "",
              grossPay: "",
              groupId: group.groupId || "",
              groupName: group.groupName || "",
              groupUserId: member.memberId || "",
              groupUserName: member.memberName || "",
              note: "",
              okTime: "",
              startTime: "",
              status: -1, // 默认的 status 为 -1 (待通知)
              unloadWeight: ""
            }))
    );

    // 将 checked 成员附加到 unloadData 中
    unloadData.value = [
      ...unloadData.value.filter(item => !checkedMembers.map(item => item.groupUserId).includes(item.groupUserId)),
      ...checkedMembers
    ];

    if (!unloadData.value.filter(item => item.status != 2).length) {
      allocateSelectTabName.value = 'success'
    } else {
      allocateSelectTabName.value = 'fail'
    }


  } else {
    console.error('Invalid groups data');
  }
  console.log('data22222', unloadData.value);
}


const imgUrl = new URL('../../../../access.jpg', import.meta.url).href

//提交分配结果

const getUnallocate = async () => {
  const response = await AllocateMembers(allocateData)
  console.log('allocateData', response)
}

//获取未分配的小组及成员

const data1 = ref([])

let groupdata = {
  groupName: '',
  pageNum: 1,
  pageSize: 10,
  status: ''
}

const getOrderId = []
const allocateMemberLoading = ref(false)
const getmemberList = async (orderId) => {

  let unallocatedUsersRes = []; // 获取未分配用户
  allocateMemberLoading.value = true
  allocateListLoading.value = true
  const response = await getUnallocatedUsers(orderId, allocateSearchData.value)
  allocateMemberLoading.value = false
  allocateListLoading.value = false
  allocateSearchData.value = {
    ...allocateSearchData.value,
    pageNum: response.data.pageNum,
    pageSize: response.data.pageSize,
    total: response.data.total,
    totalPage: response.data.totalPage
  }
  response.data.list.forEach(item => {
    unallocatedUsersRes.push({
      ...item,
      members: item.users.map(user => ({
        memberId: user.id,
        memberName: user.username,
        status: user.status,
        phone: user.phone,
        checked: "02".includes(user.status),
        disabled: "02".includes(user.status),
        // color: #ddd,
        info: null
      }))
    })
  })
  console.log('Date111111', response)
  data1.value = unallocatedUsersRes
  console.log('表的数据', data1.value)
}

const toggleAllMembers = (row) => {
  const allChecked = row.allChecked;
  row.members.forEach(member => {
    if (!member.disabled) {
      member.checked = allChecked;
      handleCheckboxChange(member, row);
    }
  });
}

const handleCheckboxChange = async (member, row) => {
  // 检查是否取消了某个成员的勾选
  if (!member.checked) {
    row.allChecked = false; // 取消全选勾选
  } else {
    // 检查是否所有成员都被勾选
    row.allChecked = row.members.every(m => m.checked);
  }

  if ("14".includes(member.status) && member.checked) {
    const msgList = [`${member.memberName}已拒绝过本订单，是否再次分配？`, `${member.memberName}在本订单上次分配时没有及时确认，是否再次分配？`]
    await ElMessageBox.confirm(
        member.status == 1 ? msgList[0] : msgList[1],
        '注意',
        {
          confirmButtonText: '分配',
          cancelButtonText: '暂不分配',
          type: 'warning',
        }
    )
        .then(() => {
          ElMessage({
            type: 'success',
            message: '已将该人员添加至待通知队伍',
          })
        })
        .catch(() => {
          member.checked = false;
          row.allChecked = false
          ElMessage({
            type: 'info',
            message: '已取消分配该人员',
          })
          return
        })
  }

  console.log('member', member)
  console.log('表的数据', data1.value)
  await getunload(allocateData.orderId)

}

const objectSpanMethod = ({rowIndex, columnIndex}) => {
  // 合并操作列
  if (columnIndex === 2) {
    if (rowIndex === 0) {
      return {
        rowspan: data1.length, // 将最后一列的所有行合并成一个
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
  // 其他列不需要合并
  return {
    rowspan: 1,
    colspan: 1,
  };
};

const dialogTableVisible6 = ref(false)
let Monorderid = []
//收款信息录入
const moneyCheck = (row) => {
  dialogTableVisible6.value = true
  Monorderid = row.orderId
  //let response = confirmMoney(res)

}


const rules = reactive<FormRules<RuleForm>>({
  accessSn: [
    {required: true, message: 'Please input Activity order_sn', trigger: 'blur'},
    {min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur'},
  ],

  accessTime: [
    {
      type: 'date',
      //required: true,
      message: 'Please pick a date',
      trigger: 'change',
    },
  ],
  shopSn: [
    {
      type: 'date',
      //required: true,
      message: 'Please pick a time',
      trigger: 'change',
    },
  ],
  shopOwner: [
    {
      type: 'date',
      required: true,
      message: 'Please pick a time',
      trigger: 'change',
    },
  ],
  truckLicense: [
    {
      type: 'date',
      //required: true,
      message: 'Please pick a time',
      trigger: 'change',
    },
  ],
  grossWeight: [
    {
      type: 'date',
      required: true,
      message: 'Please pick a time',
      trigger: 'change',
    },
  ],
  tareWeight: [
    {
      type: 'date',
      //required: true,
      message: 'Please pick a time',
      trigger: 'change',
    },
  ],
  goodWeight: [
    {
      type: 'date',
      //required: true,
      message: 'Please pick a time',
      trigger: 'change',
    },
  ],

})

let searchForm = ref({
  orderSn: '',
  stallNum: '',
  status: '',
  pageNum: 1,
  pageSize: 10,

})
const handleSearch = async () => {

  //console.log('查询内容1', searchForm.value)
  //console.log('查询内容pageSize', searchForm.value.pageSize)
  let res = await orderList(searchForm)
  list.value = res.data.list
  console.log('res', res)


}
</script>
<style scoped>
.operate-button-container {
  float: right;
  margin-right: 20px
}

.table-container {
  margin-top: 20px;
}

.input-width {
  width: 203px;
}

.container-inut {
  display: inline-block;
  margin-left: 20px;
}

.container {
  display: flex;
  /* 启用Flexbox布局 */
  justify-content: space-between;

  /* 子元素之间的空间平均分布 */
  padding: 10px;
}

.module {
  flex: 1;
  /* 每个模块占据相同的空间 */
  margin: 5px;
  /* 设置模块之间的间隔 */
  padding: 20px;
  text-align: center;
  /* 文本居中显示 */
}


/* 图片样式 */
.image-container1 {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  width: auto;
  height: auto;
  padding: 10px;
}

.el-image {
  max-width: 100%; /* 确保图片最大宽度不超过容器 */
  max-height: 300px; /* 限制最大高度 */
  height: auto; /* 保持高度自适应 */
  width: auto; /* 保持宽度自适应 */
  margin: 5px;
}

</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.module {
  margin-left: auto;
  margin-right: auto;
  max-width: 300px;
  height: 500px;
  background: #edf0f3;
  padding: 30px 30px 30px 30px;
  /* box-shadow: rgba(187, 187, 187, 1) 0 0px 20px -1px;
  -webkit-box-shadow: rgba(187, 187, 187, 1) 0 0px 20px -1px; */
  font: 12px Arial, Helvetica, sans-serif;
  color: #e7d6d6;
  border-radius: 10px;
  -webkit-border-radius: 10px;
}


.form-container {
  flex: 1; /* 自适应宽度 */
  max-width: 600px; /* 限制表单最大宽度 */
  padding-left: 20px; /* 表单和图片之间的间距 */

  border-radius: 8px;
}

.form_style {
  margin-left: auto;
  margin-right: auto;
  max-width: 500px;
  background: #FFF;
  padding: 30px 30px 30px 30px;
  box-shadow: rgba(187, 187, 187, 1) 0 0px 20px -1px;
  -webkit-box-shadow: rgba(187, 187, 187, 1) 0 0 20px -1px;
  font: 12px Arial, Helvetica, sans-serif;
  color: #666;
  border-radius: 10px;
  -webkit-border-radius: 10px
}

/*窗口拖动样式 */

:deep(.modal-wrap) {
  pointer-events: none !important;
}

:deep(.dialog-wrap) {
  pointer-events: auto !important;
  margin: 70px 0 0 70px;
}

.image-container {
  height: 720px; /* 设置容器高度 */
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  overflow: hidden; /* 超出部分隐藏 */
}

.image-container img {
  max-width: 100%; /* 最大宽度100% */
  max-height: 100%; /* 最大高度100% */
  height: auto; /* 自动高度 */
  width: auto; /* 自动宽度 */
}
</style>
